//
//  MTVerifyCodeController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/5.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

/// 键盘
import IQKeyboardManagerSwift

/// 网络

import Moya
import Result
import RxSwift
import RxCocoa
/// nav
import YPNavigationBarTransition

class MTVerifyCodeController: BaseViewController {
    
    var needSetPwd: Bool = false {
        didSet {
            
        }
    }
    
    var phone: String? {
        didSet {
            guard let phone = phone else { return }
            self.tipsLabel.attributedText = mc_addForegroundColor(text: "短信验证码已发送至: +86\(phone)", UIColor.text.x1d1a1a, range: NSRange.init(location: 10, length: 15))
        }
    }
    
    /// MTProvider
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    var countDownTime: TimeInterval = 60
    
    //返回按钮
    lazy var closeImage: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "nav_back_gray")
        imgView.contentMode = .center
        imgView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(verifyCodeController(didTapBackImage:)))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    /// 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "请输入短信验证码"
        label.font = PingFangSCSemiboldFont(24)
        label.textColor = UIColor(hex:0x2f2f2f)
        return label
    }()
    
    //提示
    lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.text = "短信验证码已发送至"
        label.font = PingFangSCRegularFont(10)
        label.textColor = UIColor(hex:0x9b9b9b)
        return label
    }()
    
    lazy var codeView: TDWVerifyCodeView = {
        let codeView = TDWVerifyCodeView.init(inputTextNum: 6)
        self.view.addSubview(codeView)
        return codeView
    }()
    
    //倒计时
    lazy var getSmsCodeButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("重新获取短信验证码", for: .normal)
        btn.setTitleColor(UIColor(hex:0x9b9b9b), for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(12)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(verifyCodeController(getSmsCodeButtonClick:)), for: .touchUpInside)
        return btn
    }()
}

extension MTVerifyCodeController {
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        startCountDown()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
        stopCountDown()
    }
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        .backgroundStyleTransparent
    }
    
    override func yp_navigationBarTintColor() -> UIColor! {
        UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        .clear
    }

    override func yp_navigationBackgroundImage(withIdentifier identifier: AutoreleasingUnsafeMutablePointer<NSString?>!) -> UIImage! {
        return nil
    }

}

extension MTVerifyCodeController{
    private func initializeUI() {
        view.backgroundColor = UIColor.theme.background
        view.addSubview(closeImage)
        view.addSubview(titleLabel)
        view.addSubview(tipsLabel)
        view.addSubview(codeView)
        view.addSubview(getSmsCodeButton)
        
        closeImage.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(StatusBarHeight+15)
            make.left.equalTo(view).offset(5)
            make.width.height.equalTo(44)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(closeImage.snp.bottom).offset(15)
            make.left.equalTo(view).offset(35)
            make.width.equalTo(200)
        }
        
        tipsLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.left.equalTo(titleLabel)
            make.width.equalTo(250)
        }
        
        codeView.snp.makeConstraints { (make) in
            make.top.equalTo(tipsLabel.snp.bottom).offset(70)
            make.left.right.equalToSuperview()
            make.height.equalTo(35)
        }
        
        getSmsCodeButton.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(codeView.snp.bottom).offset(45)
            make.height.equalTo(20)
        }
        
        // 监听验证码输入完成
        codeView.inputFinish = { [weak self] str in
            guard let weakself = self else { return }
            if weakself.needSetPwd {
                weakself.countDownTime = 60
                weakself.getSmsCodeButton.setTitle("重新获取短信验证码", for: .normal)
                weakself.getSmsCodeButton.isEnabled = true
                let vc: MTUpdatePasswordController = MTUpdatePasswordController()
                vc.param = ["mobile":weakself.phone ?? "","smsCode":str]
            weakself.navigationController?.pushViewController(vc, animated: true)
            } else {
                weakself.smsLogin(code: str)
            }
        }
    }
}

@objc
extension MTVerifyCodeController {
    private func verifyCodeController(didTapBackImage tap: UITapGestureRecognizer) {
        navigationController?.popViewController(animated: true)
    }
    
    private func verifyCodeController(getSmsCodeButtonClick sender: UIButton) {
        user_provider.rx.originRequest(.sendVerify(parameter: ["mobile":phone ?? ""])).subscribe(onNext: { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
                
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200 {
                        weakself.startCountDown()
                    } else {
                        AlertManager.presentAlertView(message: datas["message"] as? String ?? "")
                    }
                }
                break
                
            case .failure(_):
                AlertManager.presentAlertView(message: "网络错误")
                break
            }
                           
        }).disposed(by: self.disposeBag)
        
    }
}

extension MTVerifyCodeController {
    private var timerName: String {
        return "com.sendVerifyTimer"
    }
    
    /// 开始倒计时
    private func startCountDown() {
        MTTimer.default.scheduledTimer(withName: timerName, timeInterval: 1, queue: .global(), repeats: true) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.countDownTime -= 1
            dispatch_async_on_main_queue {
                weakSelf.getSmsCodeButton.setTitle("\(Int(weakSelf.countDownTime))s后重新获取短信验证信息", for: .normal)
                weakSelf.getSmsCodeButton.isEnabled = false

            }
            if weakSelf.countDownTime <= 0 {
                weakSelf.stopCountDown()
                weakSelf.countDownTime = 60
                dispatch_async_on_main_queue {
                    weakSelf.getSmsCodeButton.setTitle("重新获取短信验证码", for: .normal)
                    weakSelf.getSmsCodeButton.isEnabled = true
                }
            }
        }
    }
    
    /// 结束倒计时
    private func stopCountDown() {
        MTTimer.default.removeTimer(name: timerName)
    }
    
    private func smsLogin(code: String) {
        OpenInstallSDK.defaultManager()?.getInstallParmsCompleted({ [weak self] (appData) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                if appData?.data != nil {
                    if let inviteID = appData?.data["inviterId"] as? String, inviteID.count > 0 {
                        weakSelf.loginSms(inviteID, code: code)
                    } else {
                        weakSelf.loginSms(code: code)
                    }
                } else {
                    weakSelf.loginSms(code: code)
               }
            }
        })
    }
    
    /// 短信验证码登录
    private func loginSms(_ inviteId: String? = nil, code: String) {
        var params: [String:Any] = ["mobile": phone!,
                                    "smsCode": code]
        if let iv = inviteId {
            params.updateValue(iv, forKey: "inviterId")
        }
        
        user_provider.originRequest(.codeLogin(parameter: params), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200 {
                         if let result = datas["result"] as? [String: Any] {
                             weakself.loginReponse(with: result)
                         }
                    } else if let msg = datas["message"] as? String {
                        DispatchQueue.main.async {
                            AlertManager.presentAlertView(message: msg)
                        }
                    }
                }
                break
                
            case .failure(_):
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: "登录失败")
                }
                break
            }
        }
    }
    
    private func loginReponse(with result: [String:Any]) {
        /// 设置用户模型
        UserCenter.default.set(with: result)
        
        if let status = result["userStatus"] as? Int, let name = result["userName"] as? String, let pwd = result["userPassword"] as? String {
            switch status {
            /// 审核通过
            case 1:
                /// 弹窗
                IMLoginManager.login(name, pwd, complete: {
                    /// 设置用户模型
                    UserCenter.default.set(with: result)
                    AlertManager.presentAlertView(message: "登录成功", duration: 1) {
                        UserStatusNavigate.push(from: self, withUserStatus: status)
                    }
                    debugPrint("IM 登录成功")
                }) {
                    UserCenter.default.clear()
                    IMLoginManager.logout()
                    AlertManager.presentAlertView(message: "登录失败")
                    debugPrint("IM 登录失败")
                }
                break
            default:
                DispatchQueue.main.async {
                    UserStatusNavigate.push(from: self, withUserStatus: status)
                }
                break
            }
        } else {
            AlertManager.presentAlertView(message: "登录失败")
        }
    }


}

extension MTVerifyCodeController {
    /// 设置字体颜色
    public func mc_addForegroundColor(text: String,_ color: UIColor, range: NSRange) -> NSMutableAttributedString {
        let markAttribute = NSMutableAttributedString(string: text)
        if markAttribute.length < range.location + range.length {
            return markAttribute
        }
        
        let attrs = [NSAttributedString.Key.foregroundColor: color]
        markAttribute.addAttributes(attrs, range: range)
        return markAttribute
    }
    
    
}


